<template>
  <div
    :class="[
      'key-board-box',
      screenDir == 1 || isHscreenApp ? 'hs-key-board-box' : '',
      '$vue-keyboard',
    ]"
    v-show="show"
    ref="key-board-box"
  >
    <div
      :class="[
        'key-board-box-head-op',
        hideHead ? 'key-board-box-head-hide-head' : '',
      ]"
      @touchstart.stop
      v-if="showHeader"
    >
      <!-- 键盘设置列表 -->
      <template v-if="!hideHead">
        <template v-for="(item, index) in operationList">
          <span
            class="head-op-icon"
            :key="item.id"
            @click.prevent.stop="operateBtnFn(index, item)"
            :class="[
              operationActiveIndex == index ? 'active' : '',
              isDisabled(item) ? 'disabled' : '',
              'op-item-id-' + item.id,
            ]"
            v-if="index !== 1 || (index == 1 && emojiMapKeysLength)"
          >
            <span :class="item.classs"></span>
          </span>
        </template>
      </template>
      <span
        class="head-op-icon head-op-icon-hide"
        @click.prevent.stop="operateBtnFn(3, {})"
      >
        <span class="icon iconfont icon-arrow-right-filling icon-route"></span>
      </span>
    </div>
    <keep-alive>
      <component
        v-bind:is="currentView"
        :emojiMap="emojiMap"
        :inputValue="value"
        :getInputInfo="getInputInfo"
        :disabledInputUpdateMixKeyBoardLang="disabledInputUpdateMixKeyBoardLang"
        :keyBoardMaps="keyBoardMaps"
        @show="triggerShow"
        @submit="emitSubmit"
        ref="dynamicComponent"
      ></component>
    </keep-alive>
  </div>
</template>
<script>
import Board from "./board.vue";
import Emoji from "./emoji.vue";
import Operation from "./operation.vue";

import EventKeys from "@enu/eventKeys.js";
import { onNaticeCopyEvent } from "@utils/copyPaste.js";
import { setCurrKeyBoard } from "@devass/js/blur.js";
import BaseMixins from "../../mixins/index";
export default {
  name: "defaultKeyBoard",
  mixins: [BaseMixins],
  provide() {
    return {
      showHead: this.showHeadFn,
      rotate: this.rotate,
    };
  },
  components: {
    Board,
    Emoji,
    Operation,
  },
  props: {
    type: {
      type: [String], //NumberKeyboard 是最特殊的
      required: false,
      default: "cn", //number,zh,cn //展示键盘输入方式，默认中文，如果是number就无法切换成其他输入法
    },
    emojiMap: {
      type: Object,
      default: () => {},
    },
    //是否禁用被input组件更正默认的语言类型
    //默认否
    disabledInputUpdateMixKeyBoardLang: {
      type: Boolean,
      default: () => false,
    },
    keyBoardMaps: {
      validator: function (value) {
        return (
          String.prototype.slice.call(value) === "[object Object]",
          "cnMap" in value &&
            "enMap" in value &&
            "numberMap" in value &&
            Array.isArray(value["cnMap"]),
          Array.isArray(value["enMap"]),
          Array.isArray(value["numberMap"])
        );
      },
    },
    //隐藏头部
    hideHead: {
      type: Boolean,
      default: () => false,
    },
    //rotate，可选[0,90,-90]
    rotate: {
      validator: function (value) {
        return [0, 90, -90].indexOf(value) > -1;
      },
      default: () => 0,
    },
  },
  data() {
    return {
      show: false,
      currentView: "board",
      operationActiveIndex: 0, //切换列表高亮索引
      isNumberKeyBoard: false, //是特殊数组键盘
      operationList: [
        {
          classs: "icon iconfont icon-keyboard-26",
          id: 1,
        },
        {
          classs: "icon iconfont icon-smile",
          id: 2,
          type: "smile",
        },
        {
          classs: "icon iconfont icon-operation",
          id: 3,
        },
      ],
      top: 0,
      value: "", //输入框组件的值，不可以手动改
      windowChangeCallbackBind: null,
      windowChangeTimer: null,
      screenDir: 0, //竖屏 0 横屏1
      getInputInfo: {}, //当前获取焦点的input的信息
      showHeader: true, //显示头部
    };
  },
  computed: {
    isMix() {
      return this.getInputInfo && this.getInputInfo.type === "mix";
    },
    emojiMapKeysLength() {
      return this.emojiMap && Object.keys(this.emojiMap).length > 0;
    },
    //是固定横屏的app
    isHscreenApp() {
      return [-90, 90].indexOf(this.rotate) > -1;
    },
  },
  created() {
    //获取最新输入框的值
    this.$root.$on(EventKeys["vue-keyboard-cn-update-value"], (newV) => {
      this.value = newV;
    });
    //监听原生复制，
    this.$root.$on(
      EventKeys["vue-keyboard-cn-natice-copy"],
      this.nativeCopyCallbackWrite
    );
    // this.changeView();
    // this.$root.$on(EventKeys["vue-keyboard-cn-focus"], (data) => {
    //   //这个所有键盘都会受到影响！！
    //   let { isFocus, tmpValueNoFlash } = data;
    //   this.show = isFocus;
    //   this.value = tmpValueNoFlash; //直接引用
    //   this.getInputInfo = data;
    //   this.getInputInfo.rotate = this.rotate; //把容器旋转参数添加上去
    //   this.changeView("board");
    //   this.operationActiveIndex = 0;
    //   console.log("触发键盘出现！！！！！！！键盘", isFocus, data, data.type);
    //   //数字键盘特殊处理
    //   this.isNumberKeyBoard =
    //     this.getInputInfo.type == "PasswordInput"
    //       ? true
    //       : !!data.keyBoardOtherProps;
    //   //NumberKeyBoard键盘专用
    //   this.keyBoardOtherProps = data.keyBoardOtherProps;
    //   setCurrKeyBoard({
    //     dom: this.$refs["key-board-box"],
    //     vm: this,
    //   });
    // });
    //监听键盘关闭事件
    // this.$root.$on(EventKeys["vue-keyboard-cn-show"], (bool) => {
    //   this.show = bool;
    // });
    this.operateBtnFn(this.operationActiveIndex);
    this.windowChangeCallbackBind = this.windowChange.bind(this);
    this.windowChangeCallbackBind(1); //主动调用时候不触发blur事件
    window.addEventListener("orientationchange", this.windowChangeCallbackBind);
    window.addEventListener("resize", this.windowChangeCallbackBind);
  },
  beforeDestroy() {
    this.$root.$off(
      EventKeys["vue-keyboard-cn-natice-copy"],
      this.nativeCopyCallbackWrite
    );
    window.removeEventListener(
      "orientationchange",
      this.windowChangeCallbackBind
    );
    window.removeEventListener("resize", this.windowChangeCallbackBind);
  },
  methods: {
    showHeadFn(bool) {
      this.showHeader = bool;
    },
    triggerShow(bool) {
      this.show = bool;
    },
    isDisabled(item) {
      if (item && item.type === "smile" && !this.isMix) {
        return true;
      } else {
        return false;
      }
    },
    windowChange(tmp) {
      clearTimeout(this.windowChangeTimer);
      this.windowChangeTimer = setTimeout(() => {
        let clientWidth = document.documentElement.clientWidth;
        let clientHeight = document.documentElement.clientHeight;

        if (clientWidth > clientHeight) {
          this.screenDir = 1;
        } else {
          this.screenDir = 0;
        }
      }, 200);
      if (tmp !== 1) {
        this.$root.$emit(EventKeys["vue-keyboard-cn-show"], false);
      }
    },
    nativeCopyCallbackWrite(str) {
      //如果没有显示，直接过滤
      if (!this.show) {
        return;
      }
      if (!str) {
        return;
      }
      onNaticeCopyEvent(str); //已经做去重处理
    },
    changeView(path = "board") {
      this.currentView = path;
    },
    operateBtnFn(index, item) {
      if (this.isDisabled(item)) {
        return;
      }
      if (index != 3) {
        this.operationActiveIndex = index;
      }
      switch (index) {
        case 0:
          this.changeView("board");
          break;
        case 1:
          this.changeView("Emoji");
          break;
        case 2:
          this.changeView("Operation");
          break;
        case 3:
          this.show = false;
          //通知父组件去隐藏，父组件会通知当前激活的input失去焦点
          this.$emit("show", false);
          break;
      }
    },
    focusHandler(data) {
      //这个所有键盘都会受到影响！！
      let { isFocus, tmpValueNoFlash } = data;
      this.show = isFocus;
      this.value = tmpValueNoFlash; //直接引用
      this.getInputInfo = data;
      this.getInputInfo.rotate = this.rotate; //把容器旋转参数添加上去
      this.changeView("board");
      this.operationActiveIndex = 0;
      console.log(
        "defaultKeyboard :MIXonGloabFocusEvent",
        isFocus,
        data,
        data.type
      );
      //数字键盘特殊处理
      this.isNumberKeyBoard =
        this.getInputInfo.type == "PasswordInput"
          ? true
          : !!data.keyBoardOtherProps;
      //NumberKeyBoard键盘专用
      this.keyBoardOtherProps = data.keyBoardOtherProps;
      setCurrKeyBoard({
        dom: this.$refs["key-board-box"],
        vm: this,
      });
    },
    emitSubmit() {
      this.triggerShow(false);
      this.$emit("submit");
    },
  },
};
</script>
<style lang="scss" >
@import "@/var.scss";
.key-board-box {
  touch-action: none;
  user-select: none;
  width: 100%;
  height: 35%;
  position: fixed;
  left: 0;
  bottom: 0;
  background: $bgColor;
  padding: 5px 0;

  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  z-index: 9999;
  transform: translateZ(1px);
  * {
    margin: 0;
    padding: 0;
  }
  &.hs-key-board-box {
    height: 60%;
    max-height: 300px;
  }
  .key-board-box-head {
    background: #eee;
  }
  .icon-route {
    transform: rotate(90deg);
  }
}
</style>